//
//  SchoolRankingViewController.m
//  HotWord
//
//  Created by 贺 欢 on 13-3-3.
//
//

#import "QuestTagCategoryViewController.h"
#import "QuestTagSelectViewController.h"
#import "QuestionTagSelectCell.h"
#import "SelectTag.h"
#import "ServiceHelper.h"
#import "UserManager.h"

@interface QuestTagCategoryViewController ()<QuestTagSelectViewControllerDelegate>
{
    SelectSubTag *_selectTag;
    BOOL _haveLoaded;
    BOOL _isLoading;
}
@property (retain, nonatomic) IBOutlet UITableView *questionTagTableView;

@end

@implementation QuestTagCategoryViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
    }
    return self;
}

- (void)dealloc
{
    [_questionTagTableView release];
    [_selectTag release];
    [super dealloc];
}

- (void)viewDidUnload
{
    [self setQuestionTagTableView:nil];
    [super viewDidUnload];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    _questionTagTableView.top = self.view.height;
}


- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    
    [UIView animateWithDuration:0.4 animations:^{
        [self.view viewWithTag:10].alpha = 1;
    }];

    if (!_haveLoaded) {
        _haveLoaded = YES;
                
        if ([[UserManager sharedManager].questionTags count] > 0)
        {
            [UIView animateWithDuration:0.4
                             animations:^{
                                 _questionTagTableView.top = 0;
                             }];
        }
        else
        {
            [[ServiceHelper sharedService] requestServerForMethod:HotWordRequestTypeGetQuestionTags WithParameters:nil AndCallBackScope:self AndSuccessSel:@"getQuestionTagSuccess:" AndFailedSel:@"getQuestionTagFailed:"];
            _isLoading = YES;
            [[HTActivityIndicator currentIndicator] displayActivity:@"Loading..."];

        }
    }
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    NSIndexPath *selectIndexPath = [_questionTagTableView indexPathForSelectedRow];
    if (selectIndexPath)
    {
        [_questionTagTableView deselectRowAtIndexPath:selectIndexPath animated:YES];
    }
    [self.view viewWithTag:10].alpha = 0;
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    if (_isLoading)
    {
        [[HTActivityIndicator currentIndicator] hide];
    }
}

#pragma mark - Request

- (void)getQuestionTagSuccess:(NSObject *)result
{
    _isLoading = NO;
    if (![result isKindOfClass:[NSDictionary class]]) {
        [self.navigationController popViewControllerAnimated:YES];
        [[HTActivityIndicator currentIndicator] displayMessage:@"Has no tags!"];
        return;
    }
    NSDictionary *dic = (NSDictionary *)result;
    NSArray *tagDics = [dic objectForKey:@"tags"];
    
    for (NSDictionary *tagDic in tagDics)
    {
        SelectTag *tag = [[[SelectTag alloc] init] autorelease];
        tag.tagId = [UtilHelper getStringValue:[tagDic objectForKey:@"tagId"]];
        tag.name = [UtilHelper getStringValue:[tagDic objectForKey:@"name"]];
        NSMutableArray *subTags = [NSMutableArray array];
        NSArray *subTagDics = [tagDic objectForKey:@"subTags"];
        for (NSDictionary *subTagDic in subTagDics)
        {
            SelectSubTag *tag = [[SelectSubTag alloc] init];
            tag.tagId = [UtilHelper getStringValue:[subTagDic objectForKey:@"tagId"]];
            tag.name = [UtilHelper getStringValue:[subTagDic objectForKey:@"name"]];
            tag.superId = [UtilHelper getStringValue:[subTagDic objectForKey:@"superId"]];
            [subTags addObject:tag];
            [tag release];
        }
        
        tag.subTags = subTags;
        
        if ([tag.subTags count] > 0)
        {
            [[UserManager sharedManager].questionTags addObject:tag];
        }
    }
    
    if ([[UserManager sharedManager].questionTags count] == 0)
    {
        [self.navigationController popViewControllerAnimated:YES];
        [[HTActivityIndicator currentIndicator] displayMessage:@"Has no tags!"];
        return;
    }
    
    [[HTActivityIndicator currentIndicator] hide];
    [_questionTagTableView reloadData];
    
        
        [UIView animateWithDuration:0.4
                         animations:^{
                             _questionTagTableView.top = 0;
                         }];
    
}

- (void)getQuestionTagFailed:(NSObject *)result
{
    _isLoading = NO;
    [[HTActivityIndicator currentIndicator] displayMessage:@"Loading Failed!"];
    [self.navigationController popViewControllerAnimated:YES];
}


#pragma mark - IBAction

- (IBAction)tapOnBackBtn:(id)sender
{
    if (_delegate && [_delegate respondsToSelector:@selector(questTagCategoryViewController:didSelectTag:)] && _selectTag)
    {
        [_delegate questTagCategoryViewController:self didSelectTag:_selectTag];
    }
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - UITableViewDataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [[UserManager sharedManager].questionTags count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"QuestionTagSelectCell";
    QuestionTagSelectCell *cell = (QuestionTagSelectCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[NSBundle mainBundle] loadNibNamed:@"QuestionTagSelectCell" owner:self options:nil] objectAtIndex:0];
        cell.type = QuestionTagSelectCellTypeCategory;
        cell.selectionStyle = UITableViewCellSelectionStyleGray;
    }
    
    cell.tag = indexPath.row + 1;
    SelectTag *tag = [[UserManager sharedManager].questionTags objectAtIndex:indexPath.row];
    [cell setTitle:tag.name];
    
    return cell;
}

- (void)tableView: (UITableView*)tableView willDisplayCell: (UITableViewCell*)cell forRowAtIndexPath: (NSIndexPath*)indexPath
{

    cell.backgroundColor = [UIColor whiteColor];
}


#pragma mark - UITableViewDelegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    SelectTag *tag = [[UserManager sharedManager].questionTags objectAtIndex:indexPath.row];
    QuestTagSelectViewController *questTagSelectViewController = [[QuestTagSelectViewController alloc] initWithTag:tag];
    questTagSelectViewController.delegate = self;
    [self.navigationController pushViewController:questTagSelectViewController animated:YES];
    [questTagSelectViewController release];
    
}

#pragma mark - SchoolSelectViewControllerDelegate

- (void)questTagSelectViewController:(QuestTagSelectViewController *)viewController didSelectTag:(SelectSubTag *)tag
{
    if (_selectTag)
    {
        RELEASE_SAFELY(_selectTag);
    }
    
    _selectTag = [tag retain];
}


@end
